<template>
  <div class="role-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增角色
          </el-button>
        </div>
      </template>

      <!-- 表格区域 -->
      <mobile-table
        :data="tableData"
        :current-page="1"
        :page-size="10"
        :total="tableData.length"
        :show-pagination="false"
      >
        <!-- 桌面端表格 -->
        <template #desktop-table>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="角色名称" />
            <el-table-column prop="code" label="角色编码" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-switch
                  v-model="row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleStatusChange(row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作" width="250">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleEdit(row)">
                  编辑
                </el-button>
                <el-button type="warning" size="small" @click="handlePermission(row)">
                  权限
                </el-button>
                <el-button type="danger" size="small" @click="handleDelete(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>

        <!-- 移动端卡片 -->
        <template #mobile-card="{ row }">
          <div class="role-card">
            <div class="role-header">
              <div class="role-info">
                <h3>{{ row.name }}</h3>
                <p class="role-code">{{ row.code }}</p>
              </div>
              <div class="role-status">
                <el-switch
                  v-model="row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleStatusChange(row)"
                />
              </div>
            </div>

            <div class="role-details">
              <div class="detail-item">
                <span class="label">描述：</span>
                <span class="value">{{ row.description || '暂无描述' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ row.createTime }}</span>
              </div>
            </div>

            <div class="role-actions">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="warning" size="small" @click="handlePermission(row)">
                权限
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </div>
          </div>
        </template>
      </mobile-table>
    </el-card>

    <!-- 角色表单对话框 -->
    <mobile-form
      v-model="dialogVisible"
      :title="dialogTitle"
      :loading="submitLoading"
      @confirm="handleSubmit"
      @close="handleDialogClose"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
    </mobile-form>

    <!-- 权限分配对话框 -->
    <mobile-form
      v-model="permissionDialogVisible"
      title="权限分配"
      :loading="permissionLoading"
      @confirm="handlePermissionSubmit"
    >
      <div class="permission-tree-container">
        <el-tree
          ref="permissionTreeRef"
          :data="permissionTree"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedPermissions"
          class="permission-tree"
        />
      </div>
    </mobile-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import MobileTable from '@/components/MobileTable/index.vue'
import MobileForm from '@/components/MobileForm/index.vue'

const loading = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const submitLoading = ref(false)
const permissionLoading = ref(false)
const roleFormRef = ref()
const permissionTreeRef = ref()

const roleForm = reactive({
  id: null,
  name: '',
  code: '',
  description: ''
})

const tableData = ref([])
const checkedPermissions = ref([])
const currentRole = ref(null)

const dialogTitle = computed(() => {
  return roleForm.id ? '编辑角色' : '新增角色'
})

const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' }
  ]
}

const treeProps = {
  children: 'children',
  label: 'name'
}

// 模拟权限树数据
const permissionTree = ref([
  {
    id: 1,
    name: '系统管理',
    children: [
      { id: 11, name: '用户管理' },
      { id: 12, name: '角色管理' },
      { id: 13, name: '菜单管理' }
    ]
  },
  {
    id: 2,
    name: '内容管理',
    children: [
      { id: 21, name: '文章管理' },
      { id: 22, name: '分类管理' }
    ]
  }
])

// 模拟角色数据
const mockData = [
  {
    id: 1,
    name: '超级管理员',
    code: 'admin',
    description: '系统超级管理员，拥有所有权限',
    status: 1,
    createTime: '2023-01-01 10:00:00'
  },
  {
    id: 2,
    name: '普通用户',
    code: 'user',
    description: '普通用户，只有基本权限',
    status: 1,
    createTime: '2023-01-02 10:00:00'
  }
]

const fetchData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    tableData.value = mockData
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(roleForm, row)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    console.log('取消删除')
  }
}

const handlePermission = (row) => {
  currentRole.value = row
  // 模拟获取角色权限
  checkedPermissions.value = row.code === 'admin' ? [11, 12, 13, 21, 22] : [21]
  permissionDialogVisible.value = true
}

const handleStatusChange = async (row) => {
  try {
    ElMessage.success(`角色状态已${row.status ? '启用' : '禁用'}`)
  } catch (error) {
    ElMessage.error('状态切换失败')
    row.status = row.status ? 0 : 1
  }
}

const handleSubmit = async () => {
  if (!roleFormRef.value) return
  
  try {
    const valid = await roleFormRef.value.validate()
    if (!valid) return
    
    submitLoading.value = true
    
    // 模拟提交
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(roleForm.id ? '更新成功' : '创建成功')
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handlePermissionSubmit = async () => {
  try {
    permissionLoading.value = true
    
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    console.log('选中的权限:', checkedKeys)
    
    // 模拟提交权限
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('权限分配成功')
    permissionDialogVisible.value = false
  } catch (error) {
    ElMessage.error('权限分配失败')
  } finally {
    permissionLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  roleForm.id = null
  roleForm.name = ''
  roleForm.code = ''
  roleForm.description = ''
  if (roleFormRef.value) {
    roleFormRef.value.clearValidate()
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.role-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 移动端卡片样式 */
.role-card {
  .role-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;

    .role-info {
      flex: 1;

      h3 {
        margin: 0 0 4px 0;
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }

      .role-code {
        margin: 0;
        font-size: 14px;
        color: #666;
        font-family: monospace;
        background: #f5f5f5;
        padding: 2px 6px;
        border-radius: 3px;
        display: inline-block;
      }
    }

    .role-status {
      display: flex;
      align-items: center;
    }
  }

  .role-details {
    margin-bottom: 12px;

    .detail-item {
      display: flex;
      margin-bottom: 6px;
      font-size: 14px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        color: #666;
        min-width: 80px;
      }

      .value {
        color: #333;
        flex: 1;
        word-break: break-all;
      }
    }
  }

  .role-actions {
    display: flex;
    gap: 8px;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;
    flex-wrap: wrap;
  }
}

.permission-tree-container {
  .permission-tree {
    max-height: 400px;
    overflow-y: auto;

    @media (max-width: 768px) {
      max-height: 300px;

      :deep(.el-tree-node__content) {
        height: 40px;
        font-size: 14px;
      }

      :deep(.el-checkbox) {
        .el-checkbox__inner {
          width: 16px;
          height: 16px;
        }

        .el-checkbox__label {
          font-size: 14px;
        }
      }
    }
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .role-container {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;

    .el-button {
      width: 100%;
    }
  }
}
</style>
